package com.joinway.framework.workflow.common.service;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.joinway.framework.extension.utils.DataUtils;
import com.joinway.framework.workflow.common.bean.domain.Region;
import com.joinway.framework.workflow.common.bean.view.City;
import com.joinway.framework.workflow.common.bean.view.Provience;
import com.joinway.framework.workflow.common.constant.WorkflowConstants;
import com.joinway.framework.workflow.common.dao.WorkflowDao;

@Service
public class WorkflowService {

	private final static Logger log = LoggerFactory.getLogger(WorkflowService.class);
	
	@Autowired WorkflowDao dao;
	
	@Cacheable(WorkflowConstants.CacheName.WorkflowCache)
	public List<Provience> findAllProvience() throws Exception {
		List<Region> regions = dao.findAllRegion();
		log.info("{} regions was loaded", DataUtils.getSize(regions));
		
		List<Provience> proviences = new LinkedList<>();
		
		if(CollectionUtils.isNotEmpty(regions)){
			regions.stream().filter(r -> r.getType() == 1).forEach(r -> proviences.add(new Provience(r.getId(), r.getName())));
			
			for(Provience p : proviences){
				List<City> cities = new LinkedList<>();
				regions.stream()
					.filter(r -> r.getType() == 2 && r.getParentId() == p.getId())
					.forEach(r -> cities.add(new City(r.getId(), r.getName())));
				p.setCities(cities);
			}
		}
		
		return proviences;
	}
	
}
